/**
 * 测试mmap函数使用；
 * @author: sundx
 * @date: 2020-05-30 22:03:29
 * @Last Modified by: sundx
 * @Last Modified time: 2020-05-30 22:04:03
 */
#include <fcntl.h>
#include <iostream>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
void outError(const char *errorMessage) {
  std::cout << errorMessage << std::endl;
  exit(EXIT_FAILURE);
}
int main() {
  int fd = open("test", O_RDWR | O_CREAT | O_TRUNC, 0664);
  if (fd == -1)
    outError("open failed");
  char *p = nullptr;
  ftruncate(fd, 20);
  int len = lseek(fd, 0, SEEK_END);
  std::cout << "file len " << len << std::endl;
  p = (char *)mmap(nullptr, len, PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0);

  if (p == MAP_FAILED)
    outError("map failed");
  strcpy(p, "test");
  munmap(p, len);
  close(fd);

  return 0;
}